<template>
  <div class="container">
    <div v-if="!showView">
      <el-row justify="center">
        <el-col :xs="18" :sm="18" :md="5" :lg="5" :xl="5">
          <div style="height:90vh;display: flex;flex-direction: column;justify-content: space-between">
            <div>
              <div style="margin-top:10vh;text-align: left;margin-bottom: 10px;font-size:  25px;font-weight: bold">
                您好！
              </div>
              <div style="text-align: left;margin-bottom: 30px;font-size:  25px;font-weight: bold">
                欢迎来到宠之语
              </div>

              <div style="text-align: left;margin-bottom: 10px;font-size:  12px;font-weight: bold">
                请输入对应设备令牌
              </div>
              <el-input
                  v-model="deviceToken"
                  placeholder="设备令牌"
                  size="large"
              >
                <template #append>
                  <el-button :icon="CheckIcon" @click="checkToken"/>
                </template>
              </el-input>

            </div>

            <el-image style="width: 100%;" :src="src" fit="fill"/>

          </div>
        </el-col>
      </el-row>
    </div>
    <div v-else class="main-box">
      <div class="info-bar">
        <div>当前时间：{{ curTime }}</div>
      </div>
      <div style="position: relative;">
        <div v-if="isShowPlay" class="play-bg"></div>
        <div v-if="isShowPlay" style="position: absolute;top: calc(50% - 30px);left: calc(50% - 30px)" >
          <el-icon size="60" color="#fff" @click="playVideo">
            <VideoPlay/>
          </el-icon>
        </div>
        <video ref="videoRef" id="remote-video" autoplay playsinline muted></video>
      </div>
      <div style="display:flex;justify-content: space-around;height: auto">
        <div class="options">
          <el-icon color="#fff" size="30">
            <VideoCamera/>
          </el-icon>
          <text style="color:white;font-size: 12px">录像记录</text>
        </div>
        <div class="options">
          <text style="color:white;font-size: 25px;font-weight: bold">1</text>
          <text style="color:white;font-size: 12px">观看设备</text>
        </div>
        <div class="options" @click="toggleFullscreen">
          <el-icon color="#fff" size="30">
            <FullScreen/>
          </el-icon>
          <text style="color:white;font-size: 12px">全屏</text>
        </div>
      </div>
    </div>
    <!--        <video id="remote-video" autoplay playsinline muted></video>-->
  </div>
</template>

<script>
import {ref, onMounted, nextTick, toRefs, reactive} from 'vue';
import io from 'socket.io-client';
import {Check} from '@element-plus/icons-vue'
import {FullScreen, VideoCamera, VideoPlay} from "@element-plus/icons";
import {ElNotification} from 'element-plus'
// import {baseURL} from '@/config'
import {sendDeviceToken} from "@/api/role"

export default {
  components: {
    FullScreen, VideoCamera, VideoPlay
  },
  setup() {
    const state = reactive({
      deviceToken: "1",
      src: require("@/assets/dog-bg.png"),
      showView: false,
      curTime: null,
      isShowPlay: false,

      videoRef: null,
    })

    let socket = ref(null);

    onMounted(() => {
      const ua = window.navigator.userAgent;
      const isSafari = /^((?!chrome|android).)*safari/i.test(ua);
      const isIos = /iPad|iPhone|iPod/.test(ua) && !window.MSStream;
      console.log("isIos:" + isIos)
      state.isShowPlay = isIos
      if (isIos && !isSafari) {
        ElNotification({
          title: '提示',
          message: "为了获得最佳体验，请在 Safari 浏览器中打开本页面。",
          type: 'warning',
          duration: 10000
        })
      }

      setInterval(() => {
        state.curTime = new Date().toLocaleTimeString()
      }, 1000)
    })

    const playVideo = () => {
      console.log("Play video" + state.videoRef)
      // const video = document.getElementById('remote-video');
      // video.play();
      if(state.videoRef) state.videoRef.play()
      state.isShowPlay = false
    }


    const checkToken = async () => {
      if (!state.deviceToken) {
        ElNotification({
          title: '提示',
          message: "令牌不能为空",
          type: 'warning',
        })
      } else {
        //密码输入有误，请确认令牌是否正确
        const {data} = await sendDeviceToken({deviceToken: state.deviceToken})
        if (data) {
          ElNotification({
            title: '恭喜!',
            message: "连接成功,不要刷新哦，请稍等...",
            type: 'success',
          })
          state.showView = true
          connectServe()
        } else {
          ElNotification({
            title: '提示',
            message: "密码有误请再次尝试",
            type: 'warning',
          })
        }
      }
    }

    const connectServe = () => {
      // 创建一个 Socket.IO 连接
      // socket.value = io("https://petcode.wang");
      socket.value = io("https://stun.ggiooo.com:3000");
      
      // 标识自己为客户端
      socket.value.emit('client_Online', state.deviceToken);

      // 创建一个 RTCPeerConnection
      // const pc = new RTCPeerConnection();
      const pc = new RTCPeerConnection({
        iceServers: [
          {
            urls: 'stun:82.156.207.54:3478' // 这是你自己的 STUN 服务器
          },
          {
            urls: 'turn:82.156.207.54:3478', // 这也是你自己的 TURN 服务器
            username: 'admin',
            credential: 'petcode'
          }
        ]
      });


      // 当 RTCPeerConnection 收到音视频流时，显示在 video 元素中
      pc.ontrack = event => {
        console.log("开始收到音视频流", event.streams[0].getTracks())
        const remoteVideo = document.querySelector('#remote-video');
        if (remoteVideo) remoteVideo.srcObject = event.streams[0];
        if (state.videoRef) {
          setTimeout(()=>{
            if(state.videoRef.currentTime > 0 && !state.videoRef.paused && !state.videoRef.ended){
              state.isShowPlay = false
            }
          },1000)
        }

        event.streams[0].getTracks().forEach(function (track) {
          track.onended = function (event) {
            console.log("MediaStreamTrack has ended: ", event);
          };
        });
      };

      // 当 RTCPeerConnection 有新的 ICE candidate 时，发送给服务器
      pc.onicecandidate = event => {
        if (event.candidate) {
          console.log("发送新的 ICE candidate: ", event.candidate);
          socket.value.emit('candidate', event.candidate, {
            type: 'client',
            token: state.deviceToken
          });
        }
      };

      pc.onerror = (event) => {
        console.error("RTCPeerConnection encountered an error: ", event);
      };


      // 当接收到设备端的 offer 时，创建并发送 answer
      socket.value.on('offer', (offer) => {
        console.log("客户端收到offer设置为远程描述文件，把本地描述发送")
        pc.setRemoteDescription(new RTCSessionDescription(offer));
        pc.createAnswer()
            .then(answer => pc.setLocalDescription(answer))
            .then(() => socket.value.emit('answer', pc.localDescription, state.deviceToken));
      });

      // 当接收到设备端的 candidate 时，添加到 RTCPeerConnection 中
      socket.value.on('candidate', (candidate) => {
        console.log("添加新的 ICE candidate 到 RTCPeerConnection: ", candidate);
        pc.addIceCandidate(new RTCIceCandidate(candidate));
      });

      nextTick(() => {
        const remoteVideo = document.querySelector('#remote-video');
        if (remoteVideo) remoteVideo.muted = false;
      })
    };

    const toggleFullscreen = () => {
      const video = state.videoRef
      console.log("开始全屏播放IOS" + document.webkitFullscreenElement && video.webkitEnterFullscreen)
      console.log("开始全屏播放" + !document.fullscreenElement && video.requestFullscreen)
      if (!document.fullscreenElement && video.requestFullscreen) {
        video.requestFullscreen().catch(err => {
          alert(`Error attempting to enable full-screen mode: ${err.message} (${err.name})`);
        });
      } else if (!document.webkitFullscreenElement && video.webkitEnterFullscreen) {
        video.webkitEnterFullscreen().catch(err => {
          alert(`Error attempting to enable full-screen mode: ${err.message} (${err.name})`);
        });
      } else if (document.exitFullscreen) {
        document.exitFullscreen();
      } else if (document.webkitExitFullscreen) {
        document.webkitExitFullscreen();
        playVideo()
      }
    }

    return {...toRefs(state), socket, connectServe, CheckIcon: Check, checkToken, toggleFullscreen, playVideo};
  }
};
</script>


<style>
.main-box {
  width: calc(100% - 20px);
  padding: 10px;
  height: calc(100vh - 20px);
  display: flex;
  flex-direction: column;
  justify-content: space-evenly;
}

.container {
  font-family: 'Arial', sans-serif;
  color: #333;
}

.info-bar {
  display: flex;
  justify-content: space-between;
  padding: 10px;
  background-color: white;
  border-bottom: 1px solid #ddd;
}

#remote-video {
  width: 100%;
  height: auto;
  border-radius: 25px;
  box-shadow: 0px 5px 7px 2px rgb(0 0 0 / 17%);
  position: relative;
}

.play-bg {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
  background: url("../assets/play-bg.jpg") 100% 100% no-repeat;
  background-size: cover;;
  border-radius: 25px;
}

.play-bg::after {
  content: "";
  position: absolute;
  width: 100%;
  height: 100%;
  backdrop-filter: blur(3px);
  background: rgba(45, 45, 45, 0.34);
  top: 0;
  left: 0;
  border-radius: 23px;
}

.options {
  width: calc((100vw - 20px) / 3 - 50px);
  height: calc((100vw - 20px) / 3 - 50px);
  border-radius: 20px;
  display: flex;
  flex-direction: column;
  justify-content: space-evenly;
  align-items: center;
  padding: 10px;
  box-shadow: 0 4px 6px 1px #00000045;
  font-weight: bold;
  letter-spacing: 1px;
  text-indent: 1px;
  background: radial-gradient(55px 65px at 40% 85%, #5f5a5a, #454545, #383838);
}

/* Styles for screens that are wider than 800px */
@media screen and (min-width: 800px) {
  .options {
    width: 100px; /* fixed size */
    height: 100px;
    /* other styles */
  }
}
</style>